﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Dto.Request;
using XuanXiang.Infrastructure.Dto.Request.System;
using XuanXiang.Infrastructure.Dto.Response;
using XuanXiang.Infrastructure.Dto.Response.Goods;
using XuanXiang.Infrastructure.Dto.Response.System;
using XuanXiang.Infrastructure.EFCore.MySql;
using XuanXiang.Infrastructure.IOC;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.EFCore;
using XuanXiang.Service.Interface;

namespace XuanXiang.Service.Instance
{
    [Inject_]
    public class System_Service : Base_Service, I_System_Service
    {
        private readonly Sys_IOC _sys_IOC;
        private readonly Supplier_IOC _supplier_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly Goods_IOC _goods_IOC;

        public System_Service(Sys_IOC sys_IOC, 
            Supplier_IOC supplier_IOC,
            Login_IOC login_IOC,Goods_IOC goods_IOC)
        {
            _sys_IOC = sys_IOC;
            _supplier_IOC = supplier_IOC;
            _login_IOC = login_IOC;
            _goods_IOC = goods_IOC;
        }

        /// <summary>
        /// 新增字典
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Dictionary(Dictionary_Request_dto dto)
        {
            SysDictionary data = new SysDictionary()
            {
                Did = Config.GUID(),
                DcreateTime = DateTime.Now,
                Dexplain = dto.explain,
                DisBan = 0,
                DisType = dto.isType,
                Dname = dto.name,
                Dno = dto.no,
                Dicon = dto.icon,
                DparentId = dto.types,
                Dvalue = dto.value,
            };

            _sys_IOC._sys_Dictionary_EFCore.Add(data);
            var result = await _sys_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 检查权限
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="urls"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool Check_Right(string? uid, List<string>? urls)
        {
            //找到URL地址的所有权限
            var rights = _sys_IOC._sys_Right_EFCore.GetAll(d => urls.Contains(d.RUrl.ToUpper())
            && d.RIsBan == 0).ToList();
            if (rights.Count() == 0)
            {
                return false;
            }

            var rids = rights.Select(d => d.RId).ToList();
            return _sys_IOC._sys_User_Right_EFCore.GetAll(d => rids.Contains(d.UrRid)
            && d.UrUid == uid).Any();



        }

        /// <summary>
        /// 删除字典
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Delete_Dictionary(Delete_Dto dto)
        {
            var data = await _sys_IOC._sys_Dictionary_EFCore.GetAll(d => d.Did == dto.id).SingleOrDefaultAsync();
            _sys_IOC._sys_Dictionary_EFCore.Delete(data);
            var result = await _sys_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 获取所有字典
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Dictionarys(string? key)
        {

            //所有字典
            var all = await _sys_IOC._sys_Dictionary_EFCore.GetAll()
                .Select(d => new Dictionary_dto()
                {
                    id = d.Did,
                    name = d.Dname,
                    explain = d.Dexplain,
                    isBan = d.DisBan == 1 ? true : false,
                    isType = d.DisType,
                    no = d.Dno,
                    time = d.DcreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    value = d.Dvalue,
                    p_id = d.DparentId,
                    icon = d.Dicon

                }).ToListAsync();
            //根
            var root = all.Where(d => d.p_id == null).ToList();
            List<Dictionary_dto> list = new List<Dictionary_dto>();
            root.ForEach(d =>
            {
                list.Add(new Dictionary_dto()
                {
                    id = d.id,
                    name = d.name,
                    explain = d.explain,
                    isBan = d.isBan,
                    isType = d.isType,
                    no = d.no,
                    time = d.time,
                    value = d.value,
                    icon = d.icon,
                    children = Get_Dictionary_Children(d.id, all, key)

                });
            });

            return Get_Result(0, "ok", list);
        }

        /// <summary>
        /// 获取字典下的子级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Dictionarys_Children(string? id, string? key)
        {
            var data = await _sys_IOC._sys_Dictionary_EFCore.GetAll(d => d.DparentId == id && d.Dname.Contains(key))
                 .Select(d => new Dictionary_dto()
                 {
                     id = d.Did,
                     name = d.Dname,
                     explain = d.Dexplain,
                     isBan = d.DisBan == 1 ? true : false,
                     isType = d.DisType,
                     no = d.Dno,
                     time = d.DcreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                     value = d.Dvalue,

                 }).ToListAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取用户的菜单
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Users_Right(string uid)
        {
            // 获取用户已分配的权限ID
            var rids = _sys_IOC._sys_User_Right_EFCore.GetAll(d => d.UrUid == uid)
                .Select(d => d.UrRid).ToList();

            // 获取用户已分配的菜单权限（过滤禁用项和非菜单）
            var userRights = await _sys_IOC._sys_Right_EFCore
                .GetAll(true, o => o.RNo, d => rids.Contains(d.RId) && d.RIsBan == 0 && d.RIsMenu == 1)
                .ToListAsync();

            // 单独获取首页权限（RNo == 0），确保无论是否分配都包含
            var homeRight = await _sys_IOC._sys_Right_EFCore
                .GetAll(true, o => o.RNo, d => d.RNo == 0 && d.RIsBan == 0 && d.RIsMenu == 1)
                .FirstOrDefaultAsync();

            // 合并权限：用户已有权限 + 首页权限（去重）
            var rights = userRights.ToList();
            if (homeRight != null && !rights.Any(r => r.RId == homeRight.RId))
            {
                rights.Add(homeRight);
            }

            // 构建权限树形结构
            var root = rights.Where(d => string.IsNullOrEmpty(d.RParent)).ToList();
            List<UserRight_Dto> data = new List<UserRight_Dto>();
            root.ForEach(d =>
            {
                data.Add(new UserRight_Dto()
                {
                    id = d.RId,
                    icon = d.RIcon,
                    name = d.RName,
                    url = string.IsNullOrEmpty(d.RUrl) ? Config.GUID2() : d.RUrl,
                    children = Get_User_Right_Children(d.RId, rights)
                });
            });

            return Get_Result(0, "ok", data);
        }


        /// <summary>
        /// 获取用户菜单子级
        /// </summary>
        /// <param name="rId"></param>
        /// <param name="rights"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<UserRight_Dto> Get_User_Right_Children(string rId, List<SysRight> rights)
        {
            var root = rights.Where(d => d.RParent == rId).ToList();
            List<UserRight_Dto> data = new List<UserRight_Dto>();
            root.ForEach(d =>
            {
                data.Add(new UserRight_Dto()
                {
                    id = d.RId,
                    icon = d.RIcon,
                    name = d.RName,
                    url = d.RUrl == null ? Config.GUID2() : d.RUrl,
                    children = Get_User_Right_Children(d.RId, rights)
                });
            });

            return data;
        }

        /// <summary>
        /// 修改字典的禁用/启用
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Update_Dictionary_Ban(IsBan_Dto dto)
        {
            var data = await _sys_IOC._sys_Dictionary_EFCore
                .GetAll(d => d.Did == dto.id).SingleOrDefaultAsync();

            data!.DisBan = dto.isBan;
            _sys_IOC._sys_Dictionary_EFCore.Update(data);
            var result = await _sys_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }

        /// <summary>
        /// 获取字典的子级/递归
        /// </summary>
        /// <param name="p_id"></param>
        /// <param name="all"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<Dictionary_dto> Get_Dictionary_Children(string? p_id, List<Dictionary_dto> all, string? key)
        {
            var data = all.Where(d => d.p_id == p_id && d.name.Contains(key)).ToList();
            /*var data = _sys_IOC._sys_Dictionary_EFCore.GetAll(d => d.DparentId == p_id).ToList();*/
            List<Dictionary_dto> list = new List<Dictionary_dto>();
            data.ForEach(d =>
            {
                list.Add(new Dictionary_dto()
                {
                    id = d.id,
                    name = d.name,
                    explain = d.explain,
                    isBan = d.isBan,
                    isType = d.isType,
                    no = d.no,
                    time = d.time,
                    value = d.value,
                    icon = d.icon,
                    children = Get_Dictionary_Children(d.id, all, key)

                });
            });

            return list;
        }

        /// <summary>
        /// 获取所有的权限
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Right(string? id)
        {
            var users = await _sys_IOC._sys_User_Right_EFCore.GetAll(d => d.UrUid == id).Select(d => d.UrRid).ToListAsync();
            var rights = await _sys_IOC._sys_Right_EFCore.GetAll(true, o => o.RNo).ToListAsync();
            var root = rights.Where(d => d.RParent == null || d.RParent == "").ToList();
            List<Right_dto> data = new List<Right_dto>();
            root.ForEach(d =>
            {
                data.Add(new Right_dto()
                {
                    id = d.RId,
                    icon = d.RIcon,
                    label = d.RName,
                    desc = d.RDesc,
                    isBan = d.RIsBan == 1 ? true : false,
                    isMenu = d.RIsMenu == 1 ? true : false,
                    no = d.RNo,
                    @checked = users.Any(c => c == d.RId),
                    parent = d.RParent,
                    time = d.RCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    url = d.RUrl,
                    children = Get_Right_Children(d.RId, rights, users)

                });
            });

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取子级菜单
        /// </summary>
        /// <param name="rId"></param>
        /// <param name="rights"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<Right_dto> Get_Right_Children(string rId, List<SysRight> rights, List<string?> users)
        {
            var root = rights.Where(d => d.RParent == rId).ToList();
            var data = new List<Right_dto>();
            root.ForEach(d =>
            {
                data.Add(new Right_dto()
                {
                    id = d.RId,
                    icon = d.RIcon,
                    label = d.RName,
                    desc = d.RDesc,
                    isBan = d.RIsBan == 1 ? true : false,
                    isMenu = d.RIsMenu == 1 ? true : false,
                    no = d.RNo,
                    @checked = users.Any(c => c == d.RId),
                    parent = d.RParent,
                    time = d.RCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    url = d.RUrl,
                    children = Get_Right_Children(d.RId, rights, users)

                });
            });

            return data;
        }

        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Update_Right(Update_Right_Dto dto)
        {
            var data = await _sys_IOC._sys_Right_EFCore.GetAll(d => d.RId == dto.id).SingleOrDefaultAsync();
            data.RId = dto.id;
            data.RIsMenu = dto.isMenu;
            data.RNo = dto.no;
            data.RUrl = dto.url;
            data.RName = dto.label;
            data.RDesc = dto.desc;
            data.RIsBan = dto.isBan;
            data.RIcon = dto.icon;

            _sys_IOC._sys_Right_EFCore.Update(data);
            var result = await _sys_IOC._sys_Right_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }


        /// <summary>
        /// 新增权限
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Right(Add_Right_Dto dto)
        {
            SysRight data = new SysRight()
            {
                RId = Config.GUID(),
                RDesc = dto.desc,
                RIcon = dto.icon,
                RIsBan = 0,
                RIsMenu = dto.isMenu,
                RName = dto.name,
                RNo = dto.no,
                RParent = dto.p_id,
                RUrl = dto.url,
                RCreateTime = DateTime.Now
            };

            _sys_IOC._sys_Right_EFCore.Add(data);
            var result = await _sys_IOC._sys_Right_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Delete_Right(Delete_Dto dto)
        {
            var data = await _sys_IOC._sys_Right_EFCore.GetAll(d => d.RId == dto.id).SingleOrDefaultAsync();
            _sys_IOC._sys_Right_EFCore.Delete(data);
            var result = await _sys_IOC._sys_Right_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public async Task<Api_Result_Dto> Get_Users(Fenye_Dto dto)
        {
            var data = await _login_IOC._sysUser_EFCore.GetAll(out int total, dto.page, dto.limit, false, o => o.UcreateTime, d => d.Uname.Contains(dto.key))
                .Select(d => new Users_Dto
                {
                    id = d.Uid,
                    account = d.Uaccount,
                    isBan = d.UisBan == 1 ? true : false,
                    isActive = d.UisActive == 1 ? true : false,
                    name = d.Uname,
                    time = d.UcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),

                }).ToListAsync();

            var rights = _sys_IOC._sys_Right_EFCore.GetAll().ToList();

            data.ForEach(d =>
            {
                d.r_id = _sys_IOC._sys_User_Right_EFCore.GetAll(c => c.UrUid == d.id).Select(c => c.UrRid).ToList()!;
                var name = rights.Where(c => d.r_id.Contains(c.RId)).Select(c => c.RName).ToList();
                d.rightName = string.Join(", ", name);

            });


            return Get_Result(0, "ok", new
            {
                data = data,
                total = total,
            });
        }

        /// <summary>
        /// 用户授权
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Give_Users_Right(Right_dto dto)
        {
            //找到用户所有权限
            var iq = await _sys_IOC._sys_User_Right_EFCore.GetAll(d => d.UrUid == dto.id).ToListAsync();
            //先删除
            _sys_IOC._sys_User_Right_EFCore.DeleteRange(iq);

            //新增
            List<SysUserRight> data = new List<SysUserRight>();
            foreach (var item in dto.rights)
            {
                data.Add(new SysUserRight
                {
                    UrId = Config.GUID(),
                    UrUid = dto.id,
                    UrRid = item,
                    UrBeginTime = DateTime.Now,
                    UrCreateTime = DateTime.Now,
                    UrEndTime = null
                });
            }

            _sys_IOC._sys_User_Right_EFCore.AddRange(data);
            var result = await _sys_IOC._sys_User_Right_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }


        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Dept()
        {
            var dept = await _sys_IOC._sysDepartment_EFCore.GetAll().ToListAsync();
            var root = dept.Where(d => d.DParent == null).ToList();
            var users = _login_IOC._sysUser_EFCore.GetAll().ToList();
            List<Dept_Dto> data = new List<Dept_Dto>();
            root.ForEach(d =>
            {
                data.Add(new Dept_Dto()
                {
                    id = d.DId,
                    icon = d.DIcon,
                    label = d.DName,
                    explain = d.DExplain,
                    time = d.DCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    level = d.DLv,
                    children = Get_Dept_Children(d.DId, dept, users),
                    count = Get_Dept_UserCount(d.DId, dept, users)
                });
            });



            return Get_Result(0, "ok", data);

        }

        private int? Get_Dept_UserCount(string dId, List<SysDepartment> dept, List<SysUser> users)
        {
            // 获取当前部门的直接用户数
            int count = users.Count(u => u.UdeptId == dId);

            // 获取所有子部门
            var children = dept.Where(d => d.DParent == dId).ToList();

            // 递归获取子部门的用户数
            foreach (var child in children)
            {
                count += Get_Dept_UserCount(child.DId, dept, users) ?? 0;
            }

            return count;
        }

        /// <summary>
        /// 获取子级部门
        /// </summary>
        /// <param name="dId"></param>
        /// <param name="dept"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<Dept_Dto> Get_Dept_Children(string dId, List<SysDepartment> dept, List<SysUser> users)
        {
            var root = dept.Where(d => d.DParent == dId).ToList();
            List<Dept_Dto> data = new List<Dept_Dto>();
            root.ForEach(d =>
            {
                data.Add(new Dept_Dto()
                {
                    id = d.DId,
                    icon = d.DIcon,
                    label = d.DName,
                    explain = d.DExplain,
                    time = d.DCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    level = d.DLv,
                    children = Get_Dept_Children(d.DId, dept, users),
                    count = Get_Dept_UserCount(d.DId, dept, users)
                });
            });

            return data;
        }

        /// <summary>
        /// 获取部门下的用户
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Dept_User(Fenye_Dto dto)
        {
            var dept = _sys_IOC._sysDepartment_EFCore.GetAll().ToList();
            // 获取子级用户
            var list = GetChildrenUser(dto.id, dept);
            list.Add(dto.id);

            var data = await _login_IOC._sysUser_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.UcreateTime,
                d => list.Contains(d.UdeptId) && d.Uname.Contains(dto.key))
                .Select(d => new Users_Dto
                {
                    id = d.Uid,
                    name = d.Uname,
                    account = d.Uaccount,
                    d_id = d.UdeptId,
                    post_id = d.UpostId,
                    isActive = d.UisActive == 1 ? true : false,
                    isBan = d.UisBan == 1 ? true : false,
                    time = d.UcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                }).ToListAsync();

            // 获取所有权限和首页权限（RNo == 0）
            var allRights = _sys_IOC._sys_Right_EFCore.GetAll().ToList();
            var homeRight = allRights.FirstOrDefault(r => r.RNo == 0 && r.RIsMenu == 1);
            var homeRightName = homeRight?.RName ?? "首页"; // 默认为"首页"

            var post = _sys_IOC._sysPost_EFCore.GetAll().ToList();

            data.ForEach(d =>
            {
                d.deptName = dept.Where(c => c.DId == d.d_id).Select(c => c.DName).SingleOrDefault();
                d.deptIcon = dept.Where(c => c.DId == d.d_id).Select(c => c.DIcon).SingleOrDefault();
                d.postName = post.Where(c => c.PId == d.post_id).Select(c => c.PName).SingleOrDefault();
                d.postIcon = post.Where(c => c.PId == d.post_id).Select(c => c.PIcon).SingleOrDefault();

                // 获取用户已分配的权限ID
                var userRightIds = _sys_IOC._sys_User_Right_EFCore
                    .GetAll(c => c.UrUid == d.id)
                    .Select(c => c.UrRid)
                    .ToList()!;

                // 获取用户已分配的权限名称
                var assignedRightNames = allRights
                    .Where(c => userRightIds.Contains(c.RId))
                    .Select(c => c.RName)
                    .ToList();

                // 确保首页权限被包含（如果尚未包含）
                if (homeRight != null && !assignedRightNames.Contains(homeRightName))
                {
                    assignedRightNames.Add(homeRightName);
                }

                // 拼接权限名称
                d.rightName = string.Join(", ", assignedRightNames);
                // 权限ID包含首页权限（如果存在）
                if (homeRight != null && !userRightIds.Contains(homeRight.RId))
                {
                    d.r_id = userRightIds.Concat(new List<string> { homeRight.RId }).ToList();
                }
                else
                {
                    d.r_id = userRightIds;
                }
            });

            return Get_Result(0, "ok", new
            {
                data = data,
                total = total
            });
        }


        /// <summary>
        /// 获取子级用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dept"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<string> GetChildrenUser(string? id, List<SysDepartment> dept)
        {
            List<string> list = new List<string>();
            var children = dept.Where(d => d.DParent == id).ToList();
            children.ForEach(d =>
            {
                list.Add(d.DId);
                var son = GetChildrenUser(d.DId, dept);
                if (son.Count > 0)
                {
                    list.AddRange(son);
                }
            });

            return list;
        }

        /// <summary>
        /// 获取所有岗位
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Post(Fenye_Dto dto)
        {
            var data = await _sys_IOC._sysPost_EFCore
                .GetAll(out int total, dto.page, dto.limit, true, o => o.PLv, 
                d => d.PName.Contains(dto.key))
                .Select(d => new Post_Dto
                {
                    id = d.PId,
                    isban = d.PIsBan == 1 ? true : false,
                    explain = d.PExplain,
                    lv = d.PLv,
                    name = d.PName,
                    time = d.PCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    icon = d.PIcon
                }).ToListAsync();

            var user = _login_IOC._sysUser_EFCore.GetAll().ToList();
            data.ForEach(d =>
            {
                d.count = user.Where(c => c.UpostId == d.id).Count();
            });

            return Get_Result(0, "ok", new
            {
                data = data,
                total = total
            });
        }

        /// <summary>
        /// 新增部门
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Dept(Add_Dept_Dto dto)
        {
            SysDepartment sysDepartment = new SysDepartment()
            {
                DId = Config.GUID(),
                DName = dto.name,
                DExplain = dto.desc,
                DIcon = dto.icon,
                DIsBan = 0,
                DLv = dto.lv,
                DParent = dto.d_id,
                DCreateTime = DateTime.Now
            };
            _sys_IOC._sysDepartment_EFCore.Add(sysDepartment);
            _sys_IOC._sysDepartment_EFCore.SaveChanges();

            List<SysDepartmentPost> list = new List<SysDepartmentPost>();
            dto.postID!.ForEach(d =>
            {
                list.Add(new SysDepartmentPost()
                {
                    DpId = Config.GUID(),
                    DpDId = sysDepartment.DId,
                    DpPId = d,
                    DpCreateTime = DateTime.Now
                });
            });

            _sys_IOC._sysDepartmentPost_EFCore.AddRange(list);
            var result = await _sys_IOC._sysDepartmentPost_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Del_Dept(string? id)
        {
            var deptPost = await _sys_IOC._sysDepartmentPost_EFCore.GetAll(d => d.DpDId == id).ToListAsync();
            _sys_IOC._sysDepartmentPost_EFCore.DeleteRange(deptPost);
            _sys_IOC._sysDepartmentPost_EFCore.SaveChanges();

            var data = await _sys_IOC._sysDepartment_EFCore.GetAll(d => d.DId == id).SingleOrDefaultAsync();
            _sys_IOC._sysDepartment_EFCore.Delete(data);
            var result = await _sys_IOC._sysDepartment_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 用户禁用/启用
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> IsBan_Users(IsBan_Dto dto)
        {
            var data = await _login_IOC._sysUser_EFCore.GetAll(d => d.Uid == dto.id).SingleOrDefaultAsync();
            data!.UisBan = dto.isBan;
            _login_IOC._sysUser_EFCore.Update(data);
            var result = await _login_IOC._sysUser_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }


        /// <summary>
        /// 删除部门用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Del_User(string? id)
        {
            var data = await _login_IOC._sysUser_EFCore.GetAll(d => d.Uid == id).SingleOrDefaultAsync();
            _login_IOC._sysUser_EFCore.Delete(data);
            var result = await _login_IOC._sysUser_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }

        /// <summary>
        /// 修改部门用户信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Update_Users(Users_Dto dto)
        {

            var data = await _login_IOC._sysUser_EFCore.GetAll(d => d.Uid == dto.id).SingleOrDefaultAsync();
            data!.Uname = dto.name;
            data.Uaccount = dto.account;
            data.Uphone = dto.account;
            _login_IOC._sysUser_EFCore.Update(data);
            var result = await _login_IOC._sysUser_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 获取部门下的岗位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Dept_Post(string id)
        {
            var pids = await _sys_IOC._sysDepartmentPost_EFCore.GetAll(d => d.DpDId == id).Select(d => d.DpPId).ToListAsync();
            var data = await _sys_IOC._sysPost_EFCore
                .GetAll(d => pids.Contains(d.PId))
                .Select(d => new Post_Dto()
                {
                    id = d.PId,
                    name = d.PName
                }).ToListAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 新增部门下的用户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_User(Add_User_Dto dto)
        {
            SysUser user = new SysUser()
            {
                Uid = Config.GUID(),
                Uaccount = dto.account,
                Uname = dto.name,
                UdeptId = dto.dept_id,
                UpostId = dto.post_id,
                Uphone = dto.account,
                Ugender = dto.gender,
                Upassword = "123456",
                Usalt = null,
                UisActive = 0,
                UisBan = 0,
                UcreateTime = DateTime.Now
            };

            _login_IOC._sysUser_EFCore.Add(user);
            _login_IOC._sysUser_EFCore.SaveChanges();

            var users = await _login_IOC._sysUser_EFCore.GetAll(d => d.Uid == user.Uid).SingleOrDefaultAsync();

            var salt = Config.GUID2();
            users!.Usalt = salt;
            users.Upassword = EncryptUtil.LoginMd5("123456", salt);
            _login_IOC._sysUser_EFCore.Update(users);

            var result = await _login_IOC._sysUser_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 获取单个岗位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Single_Post(string? id)
        {
            var data =await _sys_IOC._sysPost_EFCore.GetAll(d => d.PId == id)
                .Select(d => new Post_Details_Dto(){
                id=d.PId,
                explain=d.PExplain,
                icon=d.PIcon,
                isBan=d.PIsBan==1?true:false,
                lv=d.PLv,
                name=d.PName,
                time=d.PCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).SingleOrDefaultAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取岗位下的用户
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Single_Post_Users(Fenye_Dto dto)
        {
            var data = await _login_IOC._sysUser_EFCore
               .GetAll(out int total, dto.page, dto.limit, false, o => o.UcreateTime,
               d=>d.UpostId==dto.id)
               .Select(d => new Users_Dto
               {
                   id = d.Uid,
                   name = d.Uname,
                   account = d.Uaccount,
                   d_id = d.UdeptId,
                   post_id = d.UpostId,
                   isActive = d.UisActive == 1 ? true : false,
                   isBan = d.UisBan == 1 ? true : false,
                   time = d.UcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
               }).ToListAsync();

            var rights = _sys_IOC._sys_Right_EFCore.GetAll().ToList();

            var dept=_sys_IOC._sysDepartment_EFCore.GetAll().ToList();  
            var post = _sys_IOC._sysPost_EFCore.GetAll().ToList();
            data.ForEach(d =>
            {
                d.deptName = dept.Where(c => c.DId == d.d_id).Select(c => c.DName).SingleOrDefault();
                d.deptIcon = dept.Where(c => c.DId == d.d_id).Select(c => c.DIcon).SingleOrDefault();
                d.postName = post.Where(c => c.PId == d.post_id).Select(c => c.PName).SingleOrDefault();
                d.postIcon = post.Where(c => c.PId == d.post_id).Select(c => c.PIcon).SingleOrDefault();
                d.r_id = _sys_IOC._sys_User_Right_EFCore.GetAll(c => c.UrUid == d.id).Select(c => c.UrRid).ToList()!;
                var name = rights.Where(c => d.r_id.Contains(c.RId)).Select(c => c.RName).ToList();
                d.rightName = string.Join(", ", name);
            });

            return Get_Result(0, "ok", new { data=data,
            total=total});
        }
        
        /// <summary>
        /// 修改岗位
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Update_Post(Update_Post_Dto dto)
        {
            var data = _sys_IOC._sysPost_EFCore.GetAll(d => d.PId == dto.id).Single();
            data.PName = dto.name;
            data.PLv = dto.lv;
            data.PExplain = dto.explain;
            data.PIcon = dto.icon;
            _sys_IOC._sysPost_EFCore.Update(data);
            var result = await _sys_IOC._sysPost_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 新增岗位
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Post(Add_Post_Dto dto)
        {
            SysPost post = new SysPost() {
                PId = Config.GUID(),
                PName = dto.name,
                PExplain = dto.explain,
                PIcon = dto.icon,
                PIsBan = 0,
                PLv = dto.lv,
                PCreateTime = DateTime.Now
            };

            _sys_IOC._sysPost_EFCore.Add(post);
            var result = await _sys_IOC._sysPost_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }

        /// <summary>
        /// 删除岗位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Delete_Post(string? id)
        {
            var data = _sys_IOC._sysPost_EFCore.GetAll(d => d.PId == id).SingleOrDefault();
            _sys_IOC._sysPost_EFCore.Delete(data);
            var result = await _sys_IOC._sysPost_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 获取单个字典详情(商品类型)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Single_GoodsType_Dictionary(Fenye_Dto dto)
        {
            var data = await _goods_IOC._goods_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.GcreateTime, d => d.Gtype == dto.id)
                .Select(d => new Goods_Dto { 
                id=d.Gid,
                name=d.Gname,
                explain=d.Gexplain,
                imgUrl=d.Gcover,
                inventory=d.Ginventory,
                isBan=d.GisBan==1?true:false,
                isPromote=d.GisPromote,
                isShelve=d.GisShelve==1?true:false,
                photo=d.Gcover,
                price=d.Gprice,
                sales=d.Gsales,
                specs=d.Gspecs,
                s_id=d.GSid,
                tId=d.Gtype,
                time=d.GcreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).ToListAsync();
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            var type=_sys_IOC._sys_Dictionary_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.typeName = type.Where(c => c.Did == d.tId).Select(c => c.Dname).SingleOrDefault();
                d.supplierName = supplier.Where(c => c.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
                });

            return Get_Result(0, "ok", new { 
            data=data,
            total=total
            });
           
        }
    }
}
